<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { singerManageAPI } from "@/services/singer";
import IconSearch from "@/assets/icons/IconSearch.vue";
import { debounce } from 'lodash-es';
import { ElMessage, ElMessageBox } from 'element-plus';

interface SingerVO {
  id: number;
  uid: string;
  uname: string;
  email: string | null;
  phone: string | null;
  sex: string | null;
  birthday: string | null;
  avatarUrl: string | null;
  description: string | null;
  isSinger: number;
}

const singerData = ref<SingerVO[]>([]);
const allSingerData = ref<SingerVO[]>([]);
const allUsersData = ref<SingerVO[]>([]);
const query = ref({
  uname: "",
});
const size = ref("15");
const options = [
  { value: "15", label: "15" },
  { value: "20", label: "20" },
  { value: "30", label: "30" },
  { value: "40", label: "40" },
  { value: "50", label: "50" },
];

const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);

const showDetailDialog = ref(false);
const showAddDialog = ref(false);
const showUserSelectDialog = ref(false);
const currentDetailData = ref<SingerVO | null>(null);
const formData = ref<SingerVO>({
  id: 0,
  uid: '',
  uname: '',
  email: null,
  phone: null,
  sex: null,
  birthday: null,
  avatarUrl: null,
  description: null,
  isSinger: 1
});

const selectedUser = ref<SingerVO | null>(null);
const selectionRef = ref();

const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * parseInt(size.value);
  const end = start + parseInt(size.value);
  return singerData.value.slice(start, end);
});

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

const handleSizeChange = (val: string) => {
  size.value = val;
  currentPage.value = 1;
};

const handleViewDetail = (row: SingerVO) => {
  currentDetailData.value = { ...row };
  showDetailDialog.value = true;
};

const handleEdit = (row: SingerVO) => {
  formData.value = { ...row };
  showAddDialog.value = true;
};

const handleAdd = async () => {
  try {
    loading.value = true;
    const response = await singerManageAPI().getNotSinger();
    allUsersData.value = response.data;
    showUserSelectDialog.value = true;
  } catch (error) {
    console.error('获取用户数据失败:', error);
    ElMessage.error('获取用户数据失败');
  } finally {
    loading.value = false;
  }
};

const handleUserSelect = (user: SingerVO) => {
  selectedUser.value = user;
};

const confirmAddSinger = async () => {
  if (!selectedUser.value) {
    ElMessage.warning('请先选择用户');
    return;
  }

  try {
    loading.value = true;
    await singerManageAPI().updateSinger({
      ...selectedUser.value,
      isSinger: 1,
    });
    ElMessage.success('添加歌手成功');
    showUserSelectDialog.value = false;
    selectedUser.value = null;
    getData();
  } catch (error) {
    console.error('添加歌手失败:', error);
    ElMessage.error('添加歌手失败');
  } finally {
    loading.value = false;
  }
};

const handleDelete = async (row: SingerVO) => {
  try {
    await ElMessageBox.confirm('确定要移除该歌手身份吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    
    await singerManageAPI().updateSinger({
      ...row,
      isSinger: 0,
    });
    ElMessage.success('已移除歌手身份');
    getData();
  } catch (error) {
    console.error('操作失败:', error);
    if (error !== 'cancel') {
      ElMessage.error('操作失败');
    }
  }
};

const submitForm = async () => {
  try {
    if (formData.value.id) {
      await singerManageAPI().updateSinger(formData.value);
      ElMessage.success('更新成功');
    }
    showAddDialog.value = false;
    getData();
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error('操作失败');
  }
};

const handleSearch = debounce(() => {
  if (!query.value.uname.trim()) {
    singerData.value = [...allSingerData.value];
  } else {
    const searchTerm = query.value.uname.toLowerCase();
    singerData.value = allSingerData.value.filter(singer => 
      singer.uname.toLowerCase().includes(searchTerm)
    );
  }
  currentPage.value = 1;
  total.value = singerData.value.length;
}, 500);

onMounted(() => {
  getData();
});

watch(() => query.value.uname, () => {
  handleSearch();
});

const getData = async () => {
  try {
    loading.value = true;
    const response = await singerManageAPI().getSinger("");
    allSingerData.value = response.data;
    singerData.value = [...allSingerData.value];
    total.value = singerData.value.length;
  } catch (error) {
    console.error("获取歌手数据失败:", error);
    ElMessage.error('获取歌手数据失败');
  } finally {
    loading.value = false;
  }
};

// Display formatting functions
const displayText = (value: string | null) => {
  return value ? value : '未填写';
};

const formatPhone = (phone: string | null) => {
  if (!phone) return '未填写';
  return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};

const formatDate = (dateString: string | null) => {
  if (!dateString) return '未设置';
  const date = new Date(dateString);
  return isNaN(date.getTime()) ? '无效日期' : date.toLocaleDateString();
};

const truncateText = (text: string | null, length: number = 20) => {
  if (!text) return '未填写';
  return text.length > length ? `${text.substring(0, length)}...` : text;
};

const displayAvatar = (url: string | null) => {
  return url ? url : 'https://placeholder.com/50';
};
</script>

<template>
  <div class="flex h-full gap-6">
    <div class="flex-1 bg-white rounded-lg p-4 flex flex-col justify-between min-w-0">
      <div class="flex items-center justify-between gap-8 mb-4 flex-wrap">
        <div class="flex gap-8 flex-wrap">
          <div>
            <el-input
              v-model="query.uname"
              class="input-grey"
              style="width: 200px"
              placeholder="输入歌手名搜索"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <IconSearch class="w-4 h-4 cursor-pointer" />
              </template>
            </el-input>
          </div>
        </div>
        <el-button type="primary" @click="handleAdd">
          <span>添加歌手</span>
        </el-button>
      </div>
      
      <el-table
        v-loading="loading"
        :data="paginatedTableData"
        style="width: 100%"
        height="85%"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
      >
        <el-table-column prop="uname" label="歌手名" align="center" width="120">
          <template #default="{ row }">
            {{ displayText(row.uname) }}
          </template>
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center" width="80">
          <template #default="{ row }">
            {{ displayText(row.sex) }}
          </template>
        </el-table-column>
        <el-table-column label="生日" align="center" width="120">
          <template #default="{ row }">
            {{ formatDate(row.birthday) }}
          </template>
        </el-table-column>
        <el-table-column prop="email" label="邮箱" align="center" width="180">
          <template #default="{ row }">
            {{ displayText(row.email) }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="电话" align="center" width="150">
          <template #default="{ row }">
            {{ formatPhone(row.phone) }}
          </template>
        </el-table-column>
        <el-table-column label="头像" align="center" width="120">
          <template #default="{ row }">
            <el-avatar :src="displayAvatar(row.avatarUrl)" />
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template #default="{ row }">
            {{ truncateText(row.description) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template #default="scope">
            <div class="flex justify-center gap-6">
              <button 
                class="text-[#005F59] text-[15px]"
                @click="handleEdit(scope.row)"
              >
                编辑
              </button>
              <button 
                class="text-[#FF2D55] text-[15px]"
                @click="handleDelete(scope.row)"
              >
                移除
              </button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="h-[36px] flex items-center justify-between mt-6">
        <div>
          <span class="text-[#8a8a8f] text-sm mr-2">每页结果</span>
          <el-select
            v-model="size"
            placeholder="Select"
            style="width: 70px"
            class="input-grey"
            @change="handleSizeChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-pagination
          background
          class="justify-items-end"
          layout="prev, pager, next"
          :total="total"
          :page-size="parseInt(size)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 用户选择对话框 -->
  <el-dialog 
    v-model="showUserSelectDialog" 
    title="选择用户设为歌手" 
    width="70%"
    @closed="selectedUser = null"
  >
    <el-table
      ref="selectionRef"
      :data="allUsersData"
      style="width: 100%"
      height="500"
      @selection-change="(val) => selectedUser = val.length > 0 ? val[0] : null"
      @row-click="(row) => { selectedUser = row }"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="uname" label="用户名" align="center" width="120">
        <template #default="{ row }">
          {{ displayText(row.uname) }}
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" align="center" width="180">
        <template #default="{ row }">
          {{ displayText(row.email) }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" align="center" width="150">
        <template #default="{ row }">
          {{ formatPhone(row.phone) }}
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别" align="center" width="80">
        <template #default="{ row }">
          {{ displayText(row.sex) }}
        </template>
      </el-table-column>
      <el-table-column label="生日" align="center" width="120">
        <template #default="{ row }">
          {{ formatDate(row.birthday) }}
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="showUserSelectDialog = false">取消</el-button>
      <el-button type="primary" @click="confirmAddSinger">设为歌手</el-button>
    </template>
  </el-dialog>

  <!-- 编辑对话框 -->
  <el-dialog 
    v-model="showAddDialog" 
    title="编辑歌手信息" 
    width="50%"
  >
    <el-form :model="formData" label-width="100px">
      <el-form-item label="歌手名" required>
        <el-input v-model="formData.uname" placeholder="请输入歌手名" />
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item label="电话">
        <el-input v-model="formData.phone" placeholder="请输入电话" />
      </el-form-item>
      <el-form-item label="性别">
        <el-select v-model="formData.sex" placeholder="请选择性别">
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
          <el-option label="未设置" :value="null" />
        </el-select>
      </el-form-item>
      <el-form-item label="生日">
        <el-date-picker 
          v-model="formData.birthday" 
          type="date" 
          placeholder="选择生日"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="头像URL">
        <el-input v-model="formData.avatarUrl" placeholder="请输入头像URL" />
      </el-form-item>
      <el-form-item label="描述">
        <el-input 
          v-model="formData.description" 
          type="textarea" 
          placeholder="请输入描述" 
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.icon {
  fill: currentColor;
  width: 20px;
  margin-right: 6px;
}
.input-grey {
  .el-input__wrapper {
    background: #f9f9f9;
    padding-left: 8px;
  }
  .el-select__wrapper {
    background: #f9f9f9;
  }
}
.el-table__header-wrapper {
  border-radius: 6px;
}
.table-header {
  background: #b88b7a !important;
  color: white;
  height: 50px !important;
  font-size: 15px;
  .el-table__cell {
    background: transparent !important;
    font-weight: 500;
  }
}
</style>